import useSWR from 'swr';
import { statisticsInventoryChartApi, InventoryObj } from '../api/dashboard';
import { useAuthStore2 } from '../store/useAuthStore2';

export const useInventoryDataMar = () => {
  const token = useAuthStore2((s) => s.token);
  const { data, error, isLoading } = useSWR(
    () =>
      token ? '/report/large-screen/statistics-statisticsInventoryChart' : null,
    statisticsInventoryChartApi,
  );

    /**
     * 数据聚合
     * @param data x 轴数据
     * @param list 接口数据
     * @returns 
     */
  const getSeriesData = (
    data: string[],
    list: InventoryObj[],
  ) => {
    return data.map((item) => {
      return list.find((i) => i.week === item)?.quantity1 || 0;
    });
  };

  //库存-马来仓-数据聚合， 马来仓只有 sku 库存
  const skuList = data?.skuInventoryChartList || [];
  let skuListMap: any = {};
  skuList.forEach((item) => {
    skuListMap[item?.week || ''] = {
      name: item?.dycDim2 || '',
      value: item?.quantity1 || 0,
    };
  });

  const InventoryChartMarData: {
    xAxis: string[];
    seriesData: {
      name: string;
      data: number[];
      areaTopColor: string;
      labelColor: string;
      lineStyle: string;
    }[];
  } = {
    xAxis: [],
    seriesData: [
      {
        name: '库存',
        data: [],
        areaTopColor: 'rgba(226, 143, 37, 1)',
        labelColor: 'rgba(226, 143, 37, 1)',
        lineStyle: 'rgba(226, 143, 37, 1)',
      },
    ],
  };

  InventoryChartMarData.xAxis = Object.keys(skuListMap).sort(
    function (a, b) {
      return (
        new Date(a + ':00:00').getTime() - new Date(b + ':00:00').getTime()
      );
    },
  );
    
     InventoryChartMarData.seriesData[0].data = getSeriesData(
       InventoryChartMarData?.xAxis,
       skuList,
     );

  

  return {
    InventoryChartMarData,
    isLoading,
    isError: error,
  };
};
